#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
IR 控制流表达式节点定义
"""

from dataclasses import dataclass, field
from typing import Iterator
import ast
from .base import IRExpr, build_expr_from_ast
from ..base import IRNode, get_default_ir_node


@dataclass
class IRConditional(IRExpr):
    """条件表达式节点（三元运算符）"""

    test: IRNode = field(default_factory=get_default_ir_node)
    body: IRNode = field(default_factory=get_default_ir_node)
    orelse: IRNode = field(default_factory=get_default_ir_node)
    node_type: str = "conditional"

    def get_child_nodes(self) -> Iterator[IRNode]:
        """获取所有子节点"""
        yield self.test
        yield self.body
        yield self.orelse
        yield from super().get_child_nodes()

    def build_from_ast(self, node: ast.IfExp) -> None:
        """从 AST 条件表达式节点构建 IR 条件表达式节点内容

        Args:
            node: AST 条件表达式节点
        """
        super().build_from_ast(node)
        self.source_line = getattr(node, "lineno", 0)
        self.test = build_expr_from_ast(node.test, self)
        self.body = build_expr_from_ast(node.body, self)
        self.orelse = build_expr_from_ast(node.orelse, self)
